"use strict";

// get
export function get(url, data = {}, success = "", error = "") {
    return loadData({
        type: "get",
        url,
        success,
        error,
        data,
    });
}

// post
export function post(url, data = {}, success = "", error = "") {
    return loadData({
        type: "post",
        url,
        success,
        error,
        data,
    });
}

// put
export function put(url, data = {}, success = "", error = "") {
    return loadData({
        type: "put",
        url,
        success,
        error,
        data,
    });
}

// del
export function del(url, data = {}, success = "", error = "") {
    return loadData({
        type: "delete",
        url,
        success,
        error,
        data,
    });
}

export function loadData(obj) {
    "use strict";

    // obj is null
    var obj = obj || {};

    var type, url, onprogress, success, error, data, result;
    type = obj.type || "post";
    url = obj.url || "";
    onprogress = obj.onprogress || "";
    success = obj.success || "";
    error = obj.error || ""
    data = obj.data || "";

    // 判断数据是否合法, 并且处理数据
    var toStr = Object.prototype.toString;
    var data_type = toStr.call(data);
    if (data_type === "[object Object]") {
        if (type === "post" || type === "delete") {
            data = JSON.stringify(data);
        } else if (type === "get") {
            var arr = [];
            for (var i in data) {
                arr.push(i + "=" + data[i]);
            }
            data = arr.join("&");
            if (data) {
                url += "?" + data;
            }
        }
    } else if (data_type === "[object FormData]") {

    } else {
        return typeof(error) === 'function' && error(result);
    }

    // 1. 创建 XMLHttpRequest object
    var xhr = new XMLHttpRequest();

    // 文件上传实时进度
    xhr.upload.onprogress = function (event) {
        if(event.lengthComputable){
            result = event;
            return typeof(onprogress) === 'function' && onprogress(result);
        }
    }

    // 2. 准备发送 并且 执行发送
    xhr.open(type, url, true);

    // 如果数据类型不是 object fordata 则设置 Content-type
    if (data_type !== "[object FormData]") {
        xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    }

    // 表单令牌
    var csrf_token = document.getElementsByName('csrf-token')[0];
    if (csrf_token) {
        xhr.setRequestHeader('X-CSRF-TOKEN', csrf_token.getAttribute('content'));
    }

    switch(type) {
        case "get":
            xhr.send(null);
            break;
        case "post":
        case "put":
        case "delete":
            xhr.send(data);
            break;
        default:
            return typeof(error) === 'function' && error(result);
    }

    // 3. 设置回调函数
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status === 200) {
                try {
                    result = JSON.parse(xhr.responseText);
                }catch(e) {
                    result = xhr.responseText;
                }
                return typeof(success) === "function" && success(result);
            } else if (xhr.status === 404) {
                result = "404 no request resources found";
                return typeof(error) === "function" && error(result);
            } else if (xhr.status === 500) {
                result = "500 server error !"
                return typeof(error) === "function" && error(result);
            } else {
                result = "unknown error, error code: " + xhr.status;
                return typeof(error) === "function" && error(result);
            }
        }
    }
}
